# 录入信息
# 学生类
import tkinter as tk
# 窗口
from tkinter import *
from tkinter import messagebox
from tkinter.messagebox import *
import os
import numpy as np
import ast

root = Tk()

# 窗口设计
root.geometry('420x400')

# 内置模块
la0 = Label(root, text='学生姓名：')
la0.grid(row=0, column=0)  # 0行0列

en1 = Entry(root)
en1.grid(row=0, column=1, columnspan=2)  # 0行1列，跨2列

la2 = Label(root, text='学号：')
la2.grid(row=1, column=0)  # 0行0列

en2 = Entry(root)
en2.grid(row=1, column=1, columnspan=2)  # 0行1列，跨2列

la3 = Label(root, text='学院：')
la3.grid(row=2, column=0)  # 0行0列

en3 = Entry(root)
en3.grid(row=2, column=1, columnspan=2)  # 0行1列，跨2列

la4 = Label(root, text='班级：')
la4.grid(row=3, column=0)  # 0行0列

en4 = Entry(root)
en4.grid(row=3, column=1, columnspan=2)  # 0行1列，跨2列

la5 = Label(root, text='课程：')
la5.grid(row=4, column=0)  # 0行0列

en5 = Entry(root)
en5.grid(row=4, column=1, columnspan=2)  # 0行1列，跨2列

la6 = Label(root, text='课时：')
la6.grid(row=5, column=0)  # 0行0列

en6 = Entry(root)
en6.grid(row=5, column=1, columnspan=2)  # 0行1列，跨2列

la7 = Label(root, text='学分：')
la7.grid(row=6, column=0)  # 0行0列

en7 = Entry(root)
en7.grid(row=6, column=1, columnspan=2)  # 0行1列，跨2列

la8 = Label(root, text='成绩：')
la8.grid(row=7, column=0)  # 0行0列

en8 = Entry(root)
en8.grid(row=7, column=1, columnspan=2)  # 0行1列，跨2列

la9 = Label(root, text='绩点：')
la9.grid(row=8, column=0)  # 0行0列

en9 = Entry(root)
en9.grid(row=8, column=1, columnspan=2)  # 0行1列，跨2列
en9.config(state="disabled")

la1 = Label(root, text="", anchor='w')
la1.grid(row=10, column=0, columnspan=5)

list = []


# 学生信息录入
class student:
    name = ''
    sid = ''
    college = ''
    classnum = ''
    course = ''
    time = ''
    credit = ''
    grade = ''
    gpa = ''

    # 学生类构造函数
    def __init__(self, name, sid, college, classnum, course, time, credit, grade, gpa):
        self.name = name
        self.sid = sid
        self.college = college
        self.classnum = classnum
        self.course = course
        self.time = time
        self.credit = credit
        self.grade = grade
        self.gpa = gpa

        list.append(({'姓名': name, '学号': sid, '学院': college, '班级': classnum, '课程': course, '课时': time,
                      '学分': credit, '成绩': grade, '绩点': gpa}))  # 向列表中添加学生信息
        print(list)


def join():
    a = []
    if en9.get():
        showinfo(title='消息提示框', message='请先清空！')
    else:
        grade = int(en8.get())
        gpa = ((grade / 10) - 5)
        if gpa < 0:
            gpa = 0
        en9.config(state="normal")
        en9.insert(0, str(round(gpa, 1)))
        en9.config(state="disabled")
        a.append(({'姓名': en1.get(), '学号': en2.get(), '学院': en3.get(), '班级': en4.get(), '课程': en5.get(), '课时': en6.get(),
                      '学分': en7.get(), '成绩': en8.get(), '绩点': round(gpa, 1)}))  # 向列表中添加学生信息
        if os.path.exists("student.txt"):
            print("已存在")
            txt = open("student.txt", "a", encoding='utf-8')
            txt.write(str(a) + '\n')
            txt.close()
            list.clear()
        else:
            txt = open("student.txt", "w+", encoding='utf-8')
            txt.write(str(a) + '\n')
            txt.close()
            list.clear()
            print("创建并保存成功")


def clearAll():  # 清楚原来表格的参数
    en1.delete(0, END)
    en2.delete(0, END)
    en3.delete(0, END)
    en4.delete(0, END)
    en5.delete(0, END)
    en6.delete(0, END)
    en7.delete(0, END)
    en8.delete(0, END)
    en9.config(state="normal")
    en9.delete(0, END)
    en9.config(state="disabled")
    la1.config(text="")


def insert(list):  # 插入la1标签某学生的所有信息
    txt = la1['text']
    if "姓名" not in txt:
        txt = txt + "查询到的学生信息:\n姓名:" + str(list[0][9:-1])
    if "学号" not in txt:
        txt = txt + ";  学号:" + str(list[1][8:-1])
    if "学院" not in txt:
        txt = txt + ";  学院:" + str(list[2][8:-1])
    if "班级" not in txt:
        txt = txt + ";  班级:" + str(list[3][8:-1])
    txt = txt + "\n 课程:" + str(list[4][8:-1])
    txt = txt + ";  课时:" + str(list[5][8:-1])
    txt = txt + ";  学分:" + str(list[6][8:-1])
    txt = txt + ";  成绩:" + str(list[7][8:-1])
    txt = txt + ";  绩点:" + str(list[8][6:-2])
    la1.config(text=txt)
    # en9的绩点要通过计算


def find():
    name = en1.get()
    number = en2.get()
    data = np.loadtxt('student.txt', delimiter=',', dtype=str, encoding='utf8')
    data = np.array(data)
    clearAll()

    if name and number:
        showinfo(title='消息提示框', message='不支持同时输入两个信息')
        return
    elif name == '' and number == '':
        showinfo(title='消息提示框', message='查询不能为空!')
        return
    elif number == '':  # 必须分开,否则会出错
        for i in range(len(data)):
            if str(name) == str(data[i][0][9:-1]):
                insert(data[i])
    elif name == "":  # 必须分开,否则会出错
        for i in range(len(data)):
            if int(number) == int(data[i][1][8:-1]):
                print(" ".join(data[i]))
                insert(data[i])
    return


def Delete():
    student_del = student(en1.get(), en2.get(), en3.get(), en4.get(), en5.get(), en6.get(), en7.get(), en8.get(), en9.get())
    canseach=False
    for attr, value in student_del.__dict__.items():
        if value!='':
            canseach=True
    if canseach:
        found = False
        with open("student.txt", "r+", encoding="utf-8") as studentfile:
            studentLines = studentfile.readlines()
            for studentLine in studentLines:
                studentinfo = ast.literal_eval(studentLine[1:len(studentLine) - 2])
                for attr, value in student_del.__dict__.items():
                    if attr=='sid':
                        attr_key='学号'
                    elif attr=='name':
                        attr_key='姓名'
                    elif attr == 'college':
                        attr_key = '学院'
                    elif attr == 'class':
                        attr_key = '班级'
                    elif attr == 'course':
                        attr_key = '课程'
                    elif attr == 'time':
                        attr_key = '课时'
                    elif attr == 'grade':
                        attr_key = '成绩'
                    elif attr == 'credit':
                        attr_key = '成绩'
                    if value == '':
                        continue
                    else:
                        if studentinfo[attr_key] != value:
                            found = False
                            break
                        else:
                            found=True
                if found:
                    pass
                else:
                    with open("new_student.txt", "a", encoding="utf-8") as new_studentfile:
                        new_studentfile.write(studentLine)
        if found:
            delete_found = askyesno(title='消息提示框',message='找到匹配数据，是否执行删除？（若有多条数据匹配，将全部删除）')
            if delete_found:
                os.remove('student.txt')
                if os.path.isfile('new_student.txt'):
                    os.rename('new_student.txt', 'student.txt')
                showinfo(title='消息提示框', message='删除成功')
            else:
                os.remove('new_student.txt')
        else:
            os.remove('new_student.txt')
            showinfo(title='消息提示框', message='没有找到与当前数据对应的数据')
    else:
        showinfo(title='消息提示框', message='请至少输入一条信息后使用删除')
    list.clear()

import ast

def get_grade_point(score):
    gpa = (int(en8.get()) / 10)-5
    if gpa > 0:
        return round(gpa,2)
    else:
        gpa = 0
        return gpa

def change():
    target_name = en1.get()  # 获取需要修改的学生姓名
    target_course = en5.get()  # 获取需要修改的课程名称

    with open("student.txt", "r+", encoding="utf-8") as studentfile:
        studentLines = studentfile.readlines()

        for i in range(len(studentLines)):
            studentLine = studentLines[i]
            studentinfo = ast.literal_eval(studentLine[1:len(studentLine) - 2])

            if studentinfo['姓名'] == target_name and studentinfo['课程'] == target_course:
                # 找到目标数据，进行修改操作
                updated_studentinfo = studentinfo.copy()  # 复制原始数据以保留未修改的项

                if en2.get().strip() != '':
                    updated_studentinfo['学号'] = en2.get()
                if en3.get().strip() != '':
                    updated_studentinfo['学院'] = en3.get()
                if en4.get().strip() != '':
                    updated_studentinfo['班级'] = en4.get()
                if en6.get().strip() != '':
                    updated_studentinfo['课时'] = en6.get()
                if en7.get().strip() != '':
                    updated_studentinfo['学分'] = en7.get()
                if en8.get().strip() != '':
                    updated_studentinfo['成绩'] = en8.get()

                # 更新绩点
                updated_studentinfo['绩点'] = get_grade_point(
                    float(updated_studentinfo['成绩']))  # 假设有一个计算绩点的函数get_grade_point

                # 将更新后的字典替换为原始数据
                studentLines[i] = '[' + str(updated_studentinfo) + ']\n'
                studentfile.seek(0)
                studentfile.writelines(studentLines)

                # 修改成功，跳出循环

                showinfo(title='消息提示框', message='修改成功')

                break


# 选项按钮 实现者：张镒
but1 = Button(root, text="录入", command=join)
but1.grid(row=9, column=0, padx=10, pady=10)

# 通过class的属性名匹配 实现者：MY
but2 = Button(root, text="查询", command=find)
but2.grid(row=9, column=1, padx=10, pady=10)

# 通过查找后的属性名匹配删除 实现者：Qbone
but3 = Button(root, text="删除", command=Delete)
but3.grid(row=9, column=2, padx=10, pady=10)

# 暂且只有录入后保存的功能，写完查找后实现修改后保存的功能，实现方法是重新保存相应list 实现者：张镒
but4 = Button(root, text="保存", command=change)
but4.grid(row=9, column=3, padx=10, pady=10)

but5 = Button(root, text="清除", command=clearAll)
but5.grid(row=9, column=4, padx=10, pady=10)

# 窗口执行
root.mainloop()
